package com.xing.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.xing.model.SubsidiaryInfo;
import com.xing.util.Util;

@Repository
public class SubsidiaryDao {

	@Resource
	private BaseDao baseDao;

	public void setBaseDao(BaseDao baseDao) {
		this.baseDao = baseDao;
	}
	
	public void addSubsidiary(SubsidiaryInfo info) {
		
		baseDao.getHibernateTemplate().save(info);
	}
	
	public void updateSubsidiary(SubsidiaryInfo info) {
		
		baseDao.getHibernateTemplate().saveOrUpdate(info);
	}
	
	public void deleteSubsidiary(List<Integer> idList) {
		String hql = "delete from SubsidiaryInfo where subsidiaryId in (:subsidiaryId)";
		
		List<ParamModel> paramModelList = new ArrayList<ParamModel>();
		paramModelList.add(new ParamModel("subsidiaryId", idList));
		
		baseDao.updateByHql(hql, paramModelList);
	}
	
	public List<SubsidiaryInfo> getList() {
		String hql = "from SubsidiaryInfo c order by c.subsidiaryId desc";
		
		return (List<SubsidiaryInfo>) baseDao.getList(hql);
		
	}
	
	public Map<String, Object> getListAndCount(List<String> conditionList, Integer page, Integer pageRow) {
		StringBuilder fetchHql = new StringBuilder();
		fetchHql.append("select new map(c.subsidiaryId as subsidiaryId,");
		fetchHql.append("c.name as name,");
		fetchHql.append("c.address as address,");
		fetchHql.append("c.phone as phone,");
		fetchHql.append("c.remark as remark");
		fetchHql.append(") ");

		StringBuilder hql = new StringBuilder();
		hql.append(" from SubsidiaryInfo c where 1=1 ");
		
		if (!Util.isEmpty(conditionList)) {
			Iterator<String> ite = conditionList.iterator();
			while (ite.hasNext()) {
				hql.append(" and ");
				hql.append(ite.next());
			}
		}

		StringBuilder orderHql = new StringBuilder();
		orderHql.append(" order by c.subsidiaryId");
		
		Map<String, Object> result = baseDao.getListAndCount(fetchHql.toString(), hql.toString(), orderHql.toString(), page, pageRow);

		return result;

	}
	
	public SubsidiaryInfo getSubsidiaryInfo(int id) {
		
		return (SubsidiaryInfo) baseDao.getHibernateTemplate().get(SubsidiaryInfo.class, id);
	}
}
